//
//  FilmViewController.m
//  iCinema
//
//  Created by Robin Daniels on 08/11/12.
//  Copyright (c) 2012 Robin Daniels. All rights reserved.
//

#import "FilmViewController.h"
#import "FilmDetailViewController.h"
#import "Film.h"
#import "JSONKit.h"
#import "VariableStore.h"

@interface FilmViewController ()

@end

@implementation FilmViewController {
    NSMutableArray *films;
    NSMutableArray *searchFilms;
}

// Spreiding van de foto's instellen
NSInteger rowMargin = 4;
NSInteger columnMargin = 4;

// Grootte van de foto's
NSInteger pictureWidth = 101;
NSInteger pictureHeight = 149;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.

    // Achtergrond instellen
    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bg.jpg"]];
    self.view.backgroundColor = background;
    
    // URL om JSON terug te krijgen van de webservice
	NSString* searchURL = [NSString stringWithFormat:@"http://%@:8080/MyCinemaWebservice/webresources/REST/films", [[VariableStore sharedInstance] global_ip]];
	
    // Variabele klaarzetten
	NSError* error = nil;
	NSURLResponse* response = nil;
	NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
	NSURL* URL = [NSURL URLWithString:searchURL];
    
    // Request verzenden
	[request setURL:URL];
	[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
	[request setTimeoutInterval:30];
	
    // Ontvangen data
	NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
	
    // Als de variabele 'error' inhoud heeft dan is er iets mis gegaan
    if (error)
	{
		NSLog(@"Error performing request %@", searchURL);

    // Geen error
	} else {
        
        // NSData omzetten naar een String met Json; Dictionary aanmaken van de json string
        NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *results = [jsonString objectFromJSONString];

        films = [[NSMutableArray alloc] init];
        
        // Variabele die helpen bij het plaatsen van de imageviews
        NSInteger rowPointer = rowMargin;
        NSInteger columnPointer = columnMargin;
        
        // Scrollview waarin de ImageButtons komen -> zo kan er gescrollt worden als er imageviews buiten beeld vallen
        UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 45, self.view.frame.size.width, self.view.frame.size.height)];
        scroll.backgroundColor=[UIColor clearColor];
        
        NSInteger positie = 0;
        
        // Voor elke film een object maken + ImageButton
        for (NSDictionary *movie in results) {
            
            // Film object aanmaken
            Film *film = [[Film alloc] init];
            film.Film_ID = [movie objectForKey:@"Film_ID"];
            film.Titel = [movie objectForKey:@"Titel"];
            film.Jaar = [movie objectForKey:@"Jaar"];
            film.Looptijd = [movie objectForKey:@"Looptijd"];
            film.KorteInhoud = [movie objectForKey:@"KorteInhoud"];
            film.Afbeelding = [movie objectForKey:@"Afbeelding"];
            film.Studio = [movie objectForKey:@"Studio"];
            film.Genre1 = [movie objectForKey:@"Genre1"];
            film.Genre2 = [movie objectForKey:@"Genre2"];
            film.Stream_url = [movie objectForKey:@"Stream_url"];
            film.Prijs = [movie objectForKey:@"Prijs"];
            film.KortingPercentage = [movie objectForKey:@"KortingPercentage"];

            // Berekeningen voor de coordinaten
            if (rowPointer >= (4*rowMargin + 3*pictureWidth)) {
                rowPointer = rowMargin;
                columnPointer += pictureHeight + columnMargin;
            }
            
            // Imagebutton aanmaken
            UIButton *imgButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [imgButton setFrame:CGRectMake(rowPointer, columnPointer, pictureWidth, pictureHeight)];
            [imgButton setBackgroundImage:[UIImage imageNamed:@"placeholder.png"] forState:UIControlStateNormal];
            [imgButton setTag: positie];
            
            // Iedere imagebutton moet een unieke tag hebben, positie++ dus
            positie++;
            
            // ButtonPress event aanhangen
            [imgButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

            // Toevoegen aan de scrollview
            [scroll addSubview:imgButton];
            
            // rowPointer schuift 1 foto en 1 marge op (=begin punt volgende)
            rowPointer += pictureWidth + rowMargin;
            
            // Foto van de ImageButton Async downloaden (= geen GUI freeze)
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:film.Afbeelding]];
                dispatch_sync(dispatch_get_main_queue(), ^{
                    [imgButton setBackgroundImage:[UIImage imageWithData:data] forState:UIControlStateNormal];
                    film.AfbeeldingData = data;
                });
            });
            
            // Film object in de films array steken (=mutable want de lengte is niet op voorhand gekent)
            [films addObject:film];
        }
        
        // Nadat alle imageviews toegevoegd zijn kan de grootte van de scrollview bepaald worden
        scroll.contentSize = CGSizeMake((pictureWidth * 3 + rowMargin * 4), (columnPointer + pictureHeight + columnMargin + 125));
        scroll.showsHorizontalScrollIndicator=NO;
        scroll.tag = 10;
        
        // Scrollview met al zijn childs toevoegen aan de view
        [self.view addSubview:scroll];                
    }
}

- (void) viewWillAppear:(BOOL)animated {
    self.parentViewController.title = @"Films";
}

-(void)buttonPressed:(UIButton *)sender {
    
    // De tag is uniek voor elke film = positie in de films array
    NSUInteger index = sender.tag;
    Film *f = [self->films objectAtIndex:index];

    // Detail view openen en het Film object meegeven
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle: nil];
    FilmDetailViewController *view = [storyboard instantiateViewControllerWithIdentifier:@"FilmDetail"];
    [view setFilm:f];
    [self.navigationController pushViewController:view animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [super viewDidUnload];
}

#pragma mark Search

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self handleSearch:searchBar];
}

- (void)handleSearch:(UISearchBar *)searchBar {
    
    // Array voor de zoekresultaten
    searchFilms = [[NSMutableArray alloc] init];
    
    NSInteger positie = 0;
        
    // Variabele die helpen bij het plaatsen van de imageviews
    NSInteger rowPointer = rowMargin;
    NSInteger columnPointer = columnMargin;
    
    // Leegmaken van de scrollview (enkel zoekresultaten mogen er in)
    UIScrollView *scroll = (UIScrollView *)[self.view viewWithTag:10];
    for (UIView *view in [scroll subviews]) {
        [view removeFromSuperview];
    };

    // Elke film afgaan om te testen op gelijkenissen met de zoekterm
    for (Film *f in films) {
        
        // Match?
        if([f.Titel.lowercaseString rangeOfString:searchBar.text.lowercaseString].location != NSNotFound) {

            // Posittie berekenen
            if (rowPointer >= (4*rowMargin + 3*pictureWidth)) {
                rowPointer = rowMargin;
                columnPointer += pictureHeight + columnMargin;
            }
            
            // ImageButton aanmaken
            UIButton *imgButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [imgButton setFrame:CGRectMake(rowPointer, columnPointer, pictureWidth, pictureHeight)];
            [imgButton setBackgroundImage:[UIImage imageNamed:@"placeholder.png"] forState:UIControlStateNormal];
            [imgButton setTag: positie];
            positie++;
            
            // Event aanhangen
            [imgButton addTarget:self action:@selector(buttonSearchPressed:) forControlEvents:UIControlEventTouchUpInside];
            
            // Toevoegen + rowPointer updaten
            [scroll addSubview:imgButton];
            rowPointer += pictureWidth + rowMargin;
            
            // Als de foto niet in het object zit wordt deze gedownload
            if (!f.AfbeeldingData) {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:f.Afbeelding]];
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        [imgButton setBackgroundImage:[UIImage imageWithData:data] forState:UIControlStateNormal];
                        f.AfbeeldingData = data;
                    });
                });
            } else {
                [imgButton setBackgroundImage:[UIImage imageWithData:f.AfbeeldingData] forState:UIControlStateNormal];
            }
            
            // Film toevoegen
            [searchFilms addObject:f];
        }
    };
    
    // Scrollview opnieuw herberekenen
    scroll.contentSize = CGSizeMake((pictureWidth * 3 + rowMargin * 4), (columnPointer + pictureHeight + columnMargin + 125));
    [searchBar resignFirstResponder]; // if you want the keyboard to go away
}

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar {

    // Invoer controle
    if([searchBar.text isEqualToString:@""]) {

        NSInteger positie = 0;
        
        // Variabele die helpen bij het plaatsen van de imageviews
        NSInteger rowPointer = rowMargin;
        NSInteger columnPointer = columnMargin;
        
        // Scrollview aanmaken
        UIScrollView *scroll = (UIScrollView *)[self.view viewWithTag:10];
        for (UIView *view in [scroll subviews]) {
            [view removeFromSuperview];
        };
        
        // Elke film afgaan en terug toevoegen
        for (Film *f in films) {
            if (rowPointer >= (4*rowMargin + 3*pictureWidth)) {
                rowPointer = rowMargin;
                columnPointer += pictureHeight + columnMargin;
            }
            
            // Knop aanmaken
            UIButton *imgButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [imgButton setFrame:CGRectMake(rowPointer, columnPointer, pictureWidth, pictureHeight)];
            [imgButton setBackgroundImage:[UIImage imageNamed:@"placeholder.png"] forState:UIControlStateNormal];
            [imgButton setTag: positie];
            positie++;
            
            // Event
            [imgButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
            
            // Toevoegen + updaten
            [scroll addSubview:imgButton];
            rowPointer += pictureWidth + rowMargin;
            
            // Foto instellen
            if (!f.AfbeeldingData) {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:f.Afbeelding]];
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        [imgButton setBackgroundImage:[UIImage imageWithData:data] forState:UIControlStateNormal];
                        f.AfbeeldingData = data;
                    });
                });
            } else {
                [imgButton setBackgroundImage:[UIImage imageWithData:f.AfbeeldingData] forState:UIControlStateNormal];
            }
        };
        
        // Grootte scrolview
        scroll.contentSize = CGSizeMake((pictureWidth * 3 + rowMargin * 4), (columnPointer + pictureHeight + columnMargin + 125));
    }
    
    // Keyboard verwijderen
    [searchBar resignFirstResponder];
}

- (void)buttonSearchPressed:(UIButton *)sender {    
    
    // Uniek nummer stelt een film voor
    NSUInteger index = sender.tag;
    
    // Film object ophalen adhv de index
    Film *f = [self->searchFilms objectAtIndex:index];
    
    // Details openen en film object meegeven
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle: nil];
    FilmDetailViewController *view = [storyboard instantiateViewControllerWithIdentifier:@"FilmDetail"];
    [view setFilm:f];
    [self.navigationController pushViewController:view animated:YES];
}

@end
